<template>
  <el-dialog v-model="open" :title="title" width="800px" append-to-body :close-on-click-modal="false">
    <el-form ref="dialogRef" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="会员卡类型" prop="name">
        <el-input v-model="form.name" placeholder="请输入会员卡类型" />
      </el-form-item>
      <el-form-item label="充值金额" prop="charge">
        <div class="dpflex">
          <el-input v-model="form.chargeStart" type="number" placeholder="起冲金额" />
          <span>至</span>
          <el-input v-model="form.chargeEnd" type="number" />
        </div>
      </el-form-item>
      <el-form-item label="折扣" prop="discountPercent">
        <el-input v-model="form.discountPercent" type="number" placeholder="折扣">
          <template #append>%</template>
        </el-input>
      </el-form-item>
      <el-form-item label="有效期" prop="validity">
        <div class="dpflex">
          <el-select v-model="form.validityType" placeholder="有效期">
            <el-option label="无限制" value="0" />
            <el-option label="天" value="1" />
            <el-option label="月" value="2" />
            <el-option label="年" value="3" />
          </el-select>
          <el-input v-show="form.validityType!='0'" v-model="form.validityValue" type="number">
            <template #append>{{ form.validityType=='1'?'天':(form.validityType=='2'?'月':'年') }}</template>
          </el-input>
        </div>
      </el-form-item>
      <el-form-item label="使用周期" prop="useDay">
        <el-checkbox v-model="form.useWorkdayFlag" label="工作日" true-label="1" false-label="0" />
        <el-checkbox v-model="form.useHolidayFlag" label="节假日" true-label="1" false-label="0" />
      </el-form-item>
      <el-form-item v-show="form.useWorkdayFlag=='1'" label="工作日" prop="useWorkday">
        <el-time-select
          v-model="form.useWorkdayStart"
          :max-time="form.useWorkdayEnd"
          class="mr-4"
          placeholder="00:00"
          start="00:00"
          end="23:30"
        />
        <span> 至 </span>
        <el-time-select
          v-model="form.useWorkdayEnd"
          :min-time="form.useWorkdayStart"
          placeholder="23:30"
          start="00:00"
          end="23:30"
        />
      </el-form-item>
      <el-form-item v-show="form.useHolidayFlag=='1'" label="节假日" prop="useHoliday">
        <el-time-select
          v-model="form.useHolidayStart"
          :max-time="form.useHolidayEnd"
          class="mr-4"
          placeholder="00:00"
          start="00:00"
          end="23:30"
        />
        <span> 至 </span>
        <el-time-select
          v-model="form.useHolidayEnd"
          :min-time="form.useHolidayStart"
          placeholder="23:30"
          start="00:00"
          end="23:30"
        />
      </el-form-item>
      <el-form-item label="余额限制">
        <el-checkbox-group v-model="form.balanceLimitArray">
          <el-checkbox v-for="a in balanceLimitArray " :key="a.label" :label="a.label" :disabled="a.disabled" />
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="使用须知">
        <el-input v-model="form.useNotice" type="textarea" />
      </el-form-item>
      <el-form-item label="状态">
        <el-radio-group v-model="form.status">
          <el-radio label="1">启用</el-radio>
          <el-radio label="0">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitForm">保 存</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </template>

  </el-dialog>
</template>

<script setup>
import { getCurrentInstance, reactive } from '@vue/runtime-core'
import { watch } from 'vue'
import { toRefs } from '@vueuse/shared'
import { modifyCard } from '@/api/ven/member'

const { proxy } = getCurrentInstance()

const props = defineProps({
  props: {
    type: Object,
    default: () => ({
      open: false,
      title: ''
    })
  }
})
const emit = defineEmits(['submitForm'])

const formBase = {
  validityType: '0',
  status: '1',
  useWorkdayFlag: '0',
  useHolidayFlag: '0'
}
const data = reactive({
  form: {
    ...formBase
  },
  rules: {
    name: [{ required: true, message: '必填', trigger: 'blur' }],
    charge: [{
      validator: (rule, value, callback) => {
        if (!form.value.chargeStart || !form.value.chargeEnd) {
          callback('必填')
          return
        } else {
          if (parseFloat(form.value.chargeStart) > parseFloat(form.value.chargeEnd)) {
            callback('输入有误')
            return
          }
        }
        callback()
      }, required: true, trigger: 'blur' }],
    discountPercent: [{
      validator: (rule, value, callback) => {
        if (!value) {
          callback('必填')
          return
        } else {
          if (value < 0 || value > 100) {
            callback('输入有误')
            return
          }
        }
        callback()
      }, required: true, trigger: 'blur' }],
    validity: [{
      validator: (rule, value, callback) => {
        if (form.value.validityType !== '0') {
          if (!form.value.validityValue) {
            callback('必填')
            return
          } else {
            if (form.value.validityValue < 0) {
              callback('输入有误')
              return
            }
          }
        }
        callback()
      }, required: true }],
    useDay: [{
      validator: (rule, value, callback) => {
        if (form.value.useWorkdayFlag === '0' && form.value.useHolidayFlag === '0') {
          callback('必填')
          return
        }
        callback()
      }, required: true, trigger: 'change' }],
    useWorkday: { validator: (rule, value, callback) => {
      if (form.value.useWorkdayFlag === '1') {
        if (!form.value.useWorkdayEnd || !form.value.useWorkdayStart) {
          callback('必填')
          return
        }
      }
      callback()
    }, required: true, trigger: 'change' },
    useHoliday: { validator: (rule, value, callback) => {
      if (form.value.useHolidayFlag === '1') {
        if (!form.value.useHolidayEnd || !form.value.useHolidayStart) {
          callback('必填')
          return
        }
      }
      callback()
    }, required: true, trigger: 'change' }
  },
  balanceLimitArray: [
    { label: '商品购买可用', disabled: false },
    { label: '场地预定可用', disabled: true }]
})
const { open, title } = toRefs(props.props)
const { form, rules, balanceLimitArray } = toRefs(data)

watch(open, (val) => {
  if (val) {
    form.value = props.props.data || { ...formBase }

    // 充值金额
    if (form.value.chargeRange) {
      form.value.chargeStart = form.value.chargeRange.split(',')[0]
      form.value.chargeEnd = form.value.chargeRange.split(',')[1]
    }
    // 工作日
    if (form.value.useWorkdayPeriod) {
      form.value.useWorkdayStart = form.value.useWorkdayPeriod.split(',')[0]
      form.value.useWorkdayEnd = form.value.useWorkdayPeriod.split(',')[1]
    }
    // 节假日
    if (form.value.useHolidayPeriod) {
      form.value.useHolidayStart = form.value.useHolidayPeriod.split(',')[0]
      form.value.useHolidayEnd = form.value.useHolidayPeriod.split(',')[1]
    }
    // 余额限制
    if (form.value.balanceLimit) {
      form.value.balanceLimitArray = []
      _.each(form.value.balanceLimit, (b, i) => {
        if (b === '1') {
          form.value.balanceLimitArray.push(balanceLimitArray.value[i].label)
        }
      })
    }
    if (!form.value.balanceLimitArray) {
      form.value.balanceLimitArray = _.chain(balanceLimitArray.value)
        .filter('disabled')
        .map('label')
        .value()
    }
  } else {
    proxy.resetForm('dialogRef')
  }
})

function submitForm() {
  proxy.$refs['dialogRef'].validate((valid) => {
    if (valid) {
      form.value.chargeRange = [form.value.chargeStart, form.value.chargeEnd].join(',')
      form.value.useWorkdayPeriod = [form.value.useWorkdayStart, form.value.useWorkdayEnd].join(',')
      form.value.useHolidayPeriod = [form.value.useHolidayStart, form.value.useHolidayEnd].join(',')

      const balanceLimit = []
      _.each(balanceLimitArray.value, (b) => {
        if (form.value.balanceLimitArray.indexOf(b.label) > -1) {
          balanceLimit.push('1')
        } else {
          balanceLimit.push('0')
        }
      })
      form.value.balanceLimit = balanceLimit.join('')

      modifyCard(form.value).then(() => {
        proxy.$modal.msgSuccess('操作成功')
        open.value = false
        emit('submitForm')
      })
    }
  })
}

function cancel() {
  open.value = false
}

</script>

<style scoped lang="scss">
.dpflex{display: flex;
  span{margin: 0 15px;}
}
</style>
